<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNav from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { ref } from 'vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

const HotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  HotList.value = res.result
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

/**
 * 滚动容器滚动到底部事件
 */
// 获取猜你喜欢组件实例
const GuessRef = ref<XtxGuessInstance>()
const onScrollToLower = () => {
  // console.log('到底了')
  // 获取到 组件实例 调用组件方法
  GuessRef.value?.getMore()
}

/**
 * 下拉刷新事件
 */
const isTriggered = ref(false)
const onRefresherrefresh = async () => {
  // 开启下拉刷新状态动画
  isTriggered.value = true
  // console.log('下拉刷新')
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  // 获取到 组件实例 调用组件方法 猜你喜欢数据重置
  GuessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    GuessRef.value?.getMore(),
  ])
  isTriggered.value = false
}
</script>

<template>
  <CustomNav />
  <!-- 1、启用下拉刷新功能。2、当滚动到底部时触发的事件处理函数。3、允许纵向滚动。 -->
  <scroll-view
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrollToLower"
    scroll-y
    class="scroll-view"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <XtxSwiper :list="bannerList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="HotList" />
      <XtxGuess ref="GuessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
